const directoryPath = 'E:\\AI输出\\格式工厂混流1';

const fs = require('node:fs');
const path = require('node:path');

fs.readdir(directoryPath, (err, files) => {
  if (err) {
    console.log('错误的文件夹内容:', err);
    return;
  }

  const renameArr = [];

  files.forEach(file => {
    const oldFilePath = path.join(directoryPath, file);

    const nfArr = file.split('.');

    const model = nfArr.length > 1 ? nfArr[nfArr.length - 1] : '';

    let newFileName = nfArr.slice(0, model ? nfArr.length - 1 : 1).join('.');

    newFileName = newFileName.replace(/^0+/, '');

    if (newFileName === '') {
      newFileName = '0';
    }

    newFileName += model ? '.' + model : '';

    const newFilePath = path.join(directoryPath, newFileName);
    renameArr.push({ oldFilePath, newFilePath });
  });

  while (renameArr.length > 0) {
    const onx = renameArr.shift();
    fs.rename(onx.oldFilePath, onx.newFilePath, error => {
      if (error) {
        console.log(`改名失败 ${onx.oldFilePath}:`, error);
      } else {
        console.log(`改名成功：从 ${onx.oldFilePath} 改为 ${onx.newFilePath}`);
      }
    });
  }
});
